<route lang="json5" type="page">
{
	style: {
		navigationStyle: 'custom',
		navigationBarTitleText: '登录',
	},
}
</route>

<template>
	<view class="page-login">
		<fly-navbar backgroundColor="transparent" leftText="登录" fixed />
		<image class="w-full h-full fixed top-0 left-0 z-1" :src="baseImg + '/my/login-bg.jpg'"></image>
		<view
			class="w-full h-full absolute top-0 left-0 z-2"
			:style="{ paddingTop: barAlbright + 'rpx' }"
		>
			<view class="w-full pt-[175rpx] flex items-center flex-col box-border">
				<image class="w-[272rpx] h-[136rpx]" :src="baseImg + '/my/login-read.png'"></image>
				<view class="w-[576rpx] h-[105rpx] justify-center items-center mt-[147rpx] box-border">
					<view class="w-full h-full relative">
						<image
							class="w-full h-full absolute left-[50%] -translate-x-[50%] top-0 z-1"
							:src="baseImg + '/my/login-btn.png'"
						></image> 
						<view
							v-if="!agreement"
							@tap="login"
							class="w-full h-full flex justify-center items-center absolute text-[#F4F7F4] text-[40rpx] left-[50%] -translate-x-[50%] top-0 z-2"
							>用户一键登录</view
						>
						<button
							v-else
							open-type="getPhoneNumber"
							@getphonenumber="getPhoneNumber"
							class="w-full h-full flex justify-center items-center absolute text-[#F4F7F4] text-[40rpx] left-[50%] -translate-x-[50%] top-0 z-2"
						>
							用户一键登录
						</button>
					</view>
				</view>
				<view class="w-full mt-4 flex justify-center items-center">
					<uni-data-checkbox
						multiple
						selectedColor="#2C80AA"
						v-model="agreement"
						:localdata="localdata"
					></uni-data-checkbox>
					<view class="flex items-center ml-1 text-[#207BA7] text-[24rpx]">
						已阅读并同意
						<text @tap="toProtocol('agreement')">《服务协议》</text>
						和
						<text @tap="toProtocol('privacy')">《隐私协议》</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { systemInfo } from '@/utils/getSystemInfo';
import { getDefaultUserInfo, OpenIdItem, getUserPhone } from '@/service/user';
import { useUserStore } from '@/store';
import auth from '@/utils/auth';

const baseImg = ref(import.meta.env.VITE_STATIC_IMAGE);
const userStore = useUserStore();

const { statusBarHeight, navHeight } = systemInfo();
const loginInfo = ref(null);
const barAlbright = ref(0);
const agreement = ref(undefined);
const localdata = ref([{ text: '', value: 0 }]);

onShow(() => {
	barAlbright.value = navHeight + statusBarHeight;
	auth.getOpenId().then((res: OpenIdItem) => {
		loginInfo.value = res;
	});
});

const login = async () => {
	if (!agreement.value) {
		uni.showToast({
			icon: 'none',
			title: '请先勾选协议',
		});
	}
};

const getPhoneNumber = async e => {
	// 用户登录，获取openId
	uni.showLoading({
		title: '登录中...',
	});
	if (e.detail.errMsg === 'getPhoneNumber:ok') {
		try {
			const info = await auth.getOpenId();
			loginInfo.value = info;
			getUserPhoneInfo(e);
		} catch (error) {
			uni.showToast({
				title: '授权失败,请重试!',
				icon: 'none',
			});
		}
	} else {
		uni.showToast({
			title: '授权失败,请重试!',
			icon: 'none',
		});
	}
};

const getUserPhoneInfo = async e => {
	// 用户允许或去手机号
	try {
		const res = await getUserPhone({
			encryptedData: e.detail.encryptedData,
			iv: e.detail.iv,
			session_key: loginInfo.value.session_key,
			openid: loginInfo.value.openid,
		});
		if (res.status_code === 200 && res.data.token?.access_token) {
			userStore.setUserInfo({
				...userStore.userInfo
				// uid:res.data.uid
			});
			
			userStore.setTokenInfo({
				...userStore.tokenInfo,
				token: res.data.token.token_type + res.data.token.access_token,
			});
			
			console.log('uid',res.data.uid);
			userStore.setUid(res.data.uid);
			// uni.hideLoading();
			getUserInfo();
		} else {
			
			uni.showToast({
				icon: 'none',
				title: res.message || '登录失败~',
			});
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '登录失败~',
		});
	}
};

const getUserInfo = async () => {
	try {
		const res = await getDefaultUserInfo();
		uni.hideLoading();
		if (res.status_code === 200) {
			if (res.data && res.data.student_id) {
				userStore.setUserInfo({ ...userStore.userInfo, ...res.data });
				uni.setStorageSync('isLogout', false);
				// 有默认账户信息
				uni.showToast({
					icon: 'none',
					title: '登录成功',
				});
				if (uni.getStorageSync('getCurrentPageUrlWithArgs')) {
					const args = uni.getStorageSync('getCurrentPageUrlWithArgs');
					//console.log(args)
					// debugger;
					switch (args.type) {
						case 'redirectTo':
							uni.redirectTo({
								url: args.url,
								success: () => {
									uni.setStorageSync('getCurrentPageUrlWithArgs', null);
								},
							});
							break;
						case 'switchTab':
							uni.switchTab({
								url: args.url,
								success: () => {
									uni.setStorageSync('getCurrentPageUrlWithArgs', null);
								},
							});
							break;
						case 'navigateTo':
							uni.navigateTo({
								url: args.url,
								success: () => {
									uni.setStorageSync('getCurrentPageUrlWithArgs', null);
								},
							});
							break;
						default:
							uni.redirectTo({
								url: '/pages/index/index',
							});
							break;
					}
				} else {
					uni.redirectTo({
						url: '/pages/index/index',
					});
				}
			} else {
				// 没有默认用户信息跳转学生管理页面
				uni.redirectTo({
					url: '/pages-user/account/index',
				});
			}
		} else {
			// 获取用户信息失败
			uni.showToast({
				icon: 'none',
				title: res.message || '用户信息获取失败,请重试',
			});
		}
	} catch (error) {
		uni.hideLoading();
	}
};

const toProtocol = (type: string) => {
	uni.navigateTo({
		url: `/pages-user/protocol/index?type=${type}`,
	});
};
</script>
<script lang="ts">
export default {
	options: { styleIsolation: 'shared' },
};
</script>

<style lang="scss" scoped>
.page-login {
	position: relative;
	box-sizing: border-box;
	width: 100%;
	min-height: 100vh;

	:deep(.uni-data-checklist .checklist-group .checklist-box) {
		margin: 0;
	}

	:deep(.uni-data-checklist .checklist-group .checklist-box .checkbox__inner) {
		background-color: transparent !important;
		border: 1px solid #2c80aa !important;
	}

	:deep(
			.uni-data-checklist .checklist-group .checklist-box.is--default.is-checked .checkbox__inner
		) {
		background-color: #2c80aa !important;
		border: 1px solid #2c80aa !important;
	}

	button {
		background-color: transparent !important;

		&::after {
			border: none !important;
		}
	}
}
</style>
